package cn.hl.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 1.从请求上下文对象中获取请求对象，再从请求对象中获取请求地址
        String requestURI = RequestContext.getCurrentContext().getRequest().getRequestURI();
        // 2.判断请求地址是否以登录、注册结尾，如果是返回false,否则，返回true
        if (requestURI.endsWith("/login") || requestURI.endsWith("/register")) {
            return false;
        }
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        // 1.获取请求上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 2.从请求头中获取token
        String token = requestContext.getRequest().getHeader("token");
        // 3.判断token是否为空，为空表示没有登录，直接响应noLogin
        if (StringUtils.isEmpty(token)) {
            // 4.获取响应对象
            HttpServletResponse response = requestContext.getResponse();
            // 5.设置响应格式和字符集
            response.setContentType("application/json;charset=utf-8");
            // 6.封装响应数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("message","请登录之后再访问！");
            map.put("resultObj","noLogin");
            String result = JSONObject.toJSONString(map);
            // 7.响应数据
            response.getWriter().write(result);
            // 8.阻止过滤器忘后面执行
            requestContext.setSendZuulResponse(false);
        }
        // 这里的返回值不用管，会被忽略
        return null;
    }
}
